#!/usr/bin/python

### CODE BY KYLE CLEMENS ###
### COPYRIGHT KYLE CLEMENS 2011 ###
### DISTRIBUTED UNDER TERMS OF THE GNU GPL V3 ###

### IMPORTS ###

from os import system as run
from os import path
from os import getcwd
from sys import argv
from getopt import gnu_getopt

### END IMPORTS ###

### START DEFAULTS ###

cwd   = getcwd()
start = 0     ## Starting part for Multi-Part
multi = False ## Boolean - If Multi-Part is enabled
parts = 0     ## Number of parts for Multi-Part
bar   = False ## Boolean - If a progress bar is wanted instead of text progress
url   = ""    ## URL set for downloading
cont  = 0     ## What byte to continue from, added to -C in curl
lz    = False ## Boolean - If a leading zero is needed before 1-9
comm  = ""    ## Curl command to process
out   = ""    ## Output name
app   = ""    ## Appendages
direc = ""    ## Directory to download to

ver  = '1.18'                   ## Version
slo  = 'Simple file downloader' ## Slogan/description
auth = 'Kyle Clemens'           ## Author
emai = 'pippin418@gmail.com'    ## Email
#name = argv[0]                 ## Program name

### END DEFAULTS ###

### START FUNCTIONS ###

def help(): # Display help function
	print "dl v%s" % ver ## Title
	print slo ## Description/slogan
	print
	print "Syntax:" ## Begin syntax explanation
	print "   dl [OPTION]... [URL/FILE]"
	print "   Example: dl 'http://www.example.com/index.html'"
	print "   Or:      dl -m --parts='13' 'http://www.example.com/part.rar'"
	print "   Notice in the above example that there is not part number in the URL. When you enter the URL, do not include the part number"
	print
	print "Options:" ## Options
	print "   -h, --help        Show this help" # Help then quit
	print "   -v, --version     Show the current version installed."
	print "   -m, --multi-part  Tell dl that it will be downloading multiple file parts" # Sets multi to True
	print "   -P, --progress    Show progress bar rather than text" # Sets bar to True
	print "   -c, --continue=   Tell dl at what byte to begin downloading (default is 0)" # Sets cont to given value
	print "   -o, --output=     Tell dl what filename to output, if none given it will output to the filename in the URL" # Sets output
	print "   -d, --directory=  Tell dl what directory to download to, default is directory dl was called from" # Sets direc
	print
	print "Multi-Part Options:"
	print "   Note that -o, --output= cannot be specified in Multi-Part download"
	print "   -p, --parts=        Set number of parts" # Sets parts to given value
	print "   -z, --leading-zero  Tell dl that a leading zero is necessary before a single-digit part number" # Sets lz to True
	print "   -s, --starting-part Set the starting part number, defaults to 1"
	print "   -P, --progress      Show progress bar rather than text" # Sets bar to True
	print "   -a, --appendages    Sets appendages. See the manpage for further explanation."	
	print "   -d, --directory=  Tell dl what directory to download to, default is directory dl was called from" # Sets direc
	print
	print "See `man dl` for more information."
	print
	quit()

def ins(com, command):
	command = command.split(" ")
	command.insert(1, com)
	command = ' '.join(command)
	return command

### END FUNCTIONS ###

### START OPTIONS/PARAMETERS ###

cmdline_params = argv[1:]
try:
	opts, args = gnu_getopt(cmdline_params, 'hp:mzc:Ps:o:a:vd:', ['help', 'parts=', 'multi-part', 'leading-zero', 'continue=', 'progress', 'starting-part=', 'output=', 'appendages=', 'version', 'directory='])
except:
	print "Unknown option, now quitting."
	quit()
for option, parameter in opts:
	if option in ('-h', '--help'): # This should be pretty straightforward...
		help()
	if option in ('-m', '--multi-part'):
		multi = True
	if option in ('-p', '--parts'):
		parts = int(parameter)
	if option in ('-z', '--leading-zero'):
		lz = True
	if option in ('-c', '--continue'):
		cont = int(parameter)
	if option in ('-P', '--progress'):
		bar = True
	if option in ('-s', '--starting-part'):
		start = int(parameter)-1
	if option in ('-o', '--output'):
		out = parameter
	if option in ('-a', '--appendages'):
		app = parameter
	if option in ('-v', '--version'):
		print "dl v"+ver
		print "Made by:"
		print auth + " <" + emai + ">\n"
		quit()
	if option in ('-d', '--directory'):
		direc = parameter
		if not path.exists(direc):
			print "Directory '%s' is not existent. Now quitting." % direc
			quit()

if len(args) == 1:
	url = args[0]
else:
	print "Use -h for help."
	quit()

### END OPTIONS/PARAMETERS ###

### START MULTI-PART DOWNLOADER ###

if multi:

	## start extension ##
	ext  = url.split('/') # Split url by /
	ext  = ext[len(ext)-1] # Set ext to the filename
	extc = ext # For checking purposes
	ext  = ext.split('.') # Split ext by . (extension separator)
	ext  = '.'+ext[len(ext)-1] # Set ext to the extension
	if extc == ext[1:]: # If there is no extension
		ext = "" # Don't set one
	else:
		pass #Otherwise, nevermind
	## end extension ##
	
	while start < parts:
		start = start + 1 # Add 1 to the part so it will eventually stop
		if lz > 0: # If leading zero is set (i.e. above 0)
			if start < 10: # Is it single digit?
				start = "0" + str(start) # Add 0 to single-digit
		if url.endswith(ext): # Does the URL have the extension?
			url = url.replace(ext, "") # Remove it if it does
		else: # Otherwise
			#print "Something happened. Make an issue at dlv1 on Google Code with the error code 125.\nDebug:\nURL:%s\nEXT:%s" % (url, ext) # Something went wrong
			#quit() # ABORT! IT'S A TRAP!
			pass # It's already been removed
		if url.endswith(app): # If URL ends with appendages
			url = url.replace(app, "") # Remove appendages
		pass
		fin = url + str(start) + app + ext ## Final url = Base url + current part number + appendages + extension
		out = fin.split("/") # Sets the output to URL
		out = out[len(out)-1] # Sets output to complete file name
		if direc == "": # If no output directory is set
			direc = cwd # Set it to directory dl was called from
		comm = "curl -o '%s/%s' '%s'" % (direc, out, fin) # Sets curl command
		if bar: # If bar = True
			comm = ins("-#", comm) # Add -#
		if path.exists(direc + out):
			exists = raw_input("File '%s' already exists. Overwrite? [Y/N] " % out)
			if exists[0] in ("y", 'Y'):
				print "Overwriting file '%s'." % out
			else:
				print "File '%s' not being overwritten." % out
				quit()
		run(comm) # Download with curl, run curl command
		start = int(start) # Return part to integer so we can continue
	quit() # Quit when you have all parts

### END MULTI-PART DOWNLOADER ###

### START DOWNLOADER ###

if out == "": # If no output value was set
	out = url.split("/") # Split the URL
	out = out[len(out)-1] # Find file name and set it to output value
if direc == "": # If no output directory is set
	direc = cwd # Set it to directory dl was called from
	if not direc.endswith('/'):
		direc = direc + '/'
	else:
		pass
comm = "curl -o '%s/%s' '%s'" % (direc, out, url) # Set curl command
if bar: # If -P is set
	comm = ins("-#", comm) # Add -#
if cont: # If cont value was set
	comm = ins("-C %s" % cont, comm)
if path.exists(direc + out):
	exists = raw_input("File '%s' already exists. Overwrite? [Y/N] " % out)
	if exists[0] in ("y", 'Y'):
		print "Overwriting file '%s'." % out
	else:
		print "File '%s' not being overwritten." % out
		quit()
run(comm) # Run curl command
quit() # We're done here

### END DOWNLOADER ###

quit() # Trailing quit() for safe keeping